const express = require("express")
const router = express.Router()

const { Category } = require("../../models")

const { NotFound } = require("http-errors")
const { success } = require("../../utils/response");


/**
 * 查询分类列表
 */
router.get("/", async (req, res, next) => {
    try {
        let query = req.query


        const currentPage = Math.abs(Number(query.currentPage)) || 1
        const pageSize = Math.abs(Number(query.pageSize)) || 10
        const offset = (currentPage - 1) * pageSize

        const condition = {
            order: [['id', 'ASC']],
            where: {},
            limit: pageSize,
            offset: offset
        }

        const { count, rows } = await Category.findAndCountAll(condition)
        success(res, "查询分类列表成功", {
            Categorys: rows,
            pagination: {
                total: count,
                currentPage,
                pageSize,

            }
        })

    } catch (err) {
        next(err);
    }
})

/**
 * 查询分类详情
 */
router.get("/:id", async (req, res, next) => {
    try {
        const categoery = await getCategory(req)
        success(res, "查询分类详情成功", { categoery })
    } catch (err) {
        next(err)
    }
})

/**
 * 创建分类
 */
router.post("/", async (req, res, next) => {
    try {
        const body = filterBody(req)
        console.log(body)
        const data = await Category.create(body)
        success(res, "创建分类成功", { data }, 201)
    } catch (err) {
        console.log(err)
        next(err)
    }
})

/**
 * 删除分类
 */
router.delete("/:id", async (req, res, next) => {
    try {
        let Category = await getCategory(req)
        await Category.destroy()
        success(res, "删除分类成功")
    } catch (err) {
        next(err)
    }
})

/**
 * 修改分类成功
 */
router.put('/:id', async (req, res, next) => {
    try {
        const Category = await getCategory(req)
        const body = filterBody(req)

        await Category.update(body)

        success(res, "修改分类成功", { Category })

    } catch (err) {
        next(err)
    }
})

function filterBody(req) {
    return {
        name: req.body.name,
        rank: req.body.rank
    }
}

async function getCategory(req) {
    const { id } = req.params
    const category = await Category.findByPk(id)

    if (!category) {
        throw new NotFound(`ID：${id}的分类未找到`)
    }
    return category
}

module.exports = router